<template>
  <div>
    <canvas @click="changeVeri" id="myCanvas" width="180" height="40"></canvas>
  </div>
</template>
<script>
import { _getVeri } from '../../api/login'
export default {
  data () {
    return {
      veri: ''
    }
  },
  created () {
    this.getVeri()
  },
  mounted () {},
  methods: {
    changeVeri () {
      //点击切换验证码
      this.getVeri()
    },
    // 获取验证码接口
    async getVeri () {
      var res = await _getVeri()
      console.log(res)
      this.veri = res.data
      // 绘制后台返回的验证码
      this.draw(this.veri)
    },
    ranDom (a, b) {
      //随机数公式
      return Math.floor(Math.random() * (b - a) + a)
    },
    ranColor () {
      //随机颜色
      return `rgb(${this.ranDom(0, 255)}, ${this.ranDom(0, 255)}, ${this.ranDom(
        0,
        255
      )})`
    },
    // 绘制验证码
    draw (txt) {
      let cxt = document.getElementById('myCanvas')
      let c = cxt.getContext('2d')
      // 清空画布
      c.clearRect(0, 0, 200, 40)
      // 绘制文字
      for (var i = 0; i < 4; i++) {
        c.font = `${this.ranDom(20, 40)}px 黑体`
        c.fillStyle = this.ranColor() //随机颜色
        c.fillText(txt[i], i * 30 + this.ranDom(10, 30), this.ranDom(15, 40))
        c.stroke()
      }
      // 绘制干扰线
      // for (var i = 0; i < 10; i++) {
      //   c.beginPath()
      //   c.moveTo(this.ranDom(0, 200), this.ranDom(0, 40))
      //   c.lineTo(this.ranDom(0, 200), this.ranDom(0, 40))
      //   c.strokeStyle = this.ranColor() //线的随机颜色
      //   c.stroke()
      // }
      // 干扰点
      // for (var j = 0; j < 40; j++) {
      //   c.beginPath()
      //   let x = this.ranDom(0, 200)
      //   let y = this.ranDom(0, 40)
      //   c.moveTo(x, y)
      //   c.lineTo(x + 2, y + 2)
      //   c.strokeStyle = this.ranColor() //线的随机颜色
      //   c.stroke()
      // }
    }
  }
}
</script>
<style lang="less" scoped>
canvas {
  background: skyblue;
}
</style>
